<template>
  <div class="container learnstyle-page">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>{{testPaperInfo.name}} (共{{testPaperInfo.questionNumber}}题 合计{{testPaperInfo.mark}}分)</span>
          <span style="float: right">剩余时间: {{timeValue}}</span>
        </div>

        <question-info
          :showNumberTitle="false"
          @openWritingBoard="openWritingBoard"
          :timeOutFlag="timeOutFlag"
          commitButtonText="提交试卷"
          @afterCommit="afterCommit"
          :questionInfoAnswerList="testPaperInfoQuestionList">
        </question-info>
      </el-card>
    </div>
</template>

<script>
    import { mapGetters } from 'vuex'
    import questionInfo from '@/components/question-info'
    export default {
        name: 'exam',
        components: {questionInfo},
        data () {
          return {
            studentExamTime: 0, // 学生考试用时
            studentExamTimer: null,
            examTime: null,
         //   timeInterval: null,
            timeTarget: null,
            endTime: null,
            timeOutFlag: false, // 是否考试时间到
            openAnswerFlag: false,
            leaveNumber: 0,
            currentQuestion: {},
            testPaperInfoQuestionList: [], // 存储用户答题答案及试题答案解析
            currentPage: 0,
            timeValue: '',
            pageSize: 1,
            totalCount: 0,
            openWritingBoardFlag: false,
            questionTypeList: [],
          }
        },

        computed: {
          ...mapGetters({
            testPaperInfo: 'common/getTestPaperInfo'
          })
        },

        beforeCreate () {

        },

        mounted () {
          if (this.testPaperInfo.examTime) {

            let examTimeObj = sessionStorage.getItem('examTime')
            if (examTimeObj) {
              this.examTime = parseInt(examTimeObj) //parseInt(examTimeObj) * 60 * 1000
            } else {
              this.examTime = this.testPaperInfo.examTime * 60 * 1000
            }
            let now =  new Date().getTime()
            this.endTime = now + this.examTime
            this.timeTarget = setInterval(() => {
              this.startTime(); // 开始倒计时
            }, 100)

          }

          this.studentExamTimer = setInterval(() => {
            this.startCountStudentExamTime() // 开始计算考试时间
          }, 1000)
          this.getPaperQuestionList()
          document.addEventListener('visibilitychange', this.visibilityChangeEvent)
        },

      destroyed() {

        document.removeEventListener('visibilitychange', this.visibilityChangeEvent)
        clearInterval(this.timeTarget)
        clearInterval(this.studentExamTimer)
      },

      methods: {

        openWritingBoard () {
          this.openWritingBoardFlag = true
        },

        startCountStudentExamTime () {
          this.studentExamTime++
        },

          // 监听页面离开事件
        visibilityChangeEvent (e) {
         // alert(document.location.href)
         /* if (document.hidden) {
            if (!this.openWritingBoardFlag) {
              this.leaveNumber++
            }
            // alert('hidden')
          } else {
            this.openWritingBoardFlag = false
            //// alert('show')
          }*/

         // alert(this.leaveNumber)
         /* this.leaveNumber++
          if (this.leaveNumber === 6) {
            console.log('作弊, 系统自动提交')
          }
          if (this.leaveNumber % 2 !== 0) {
            this.$alert('考试中请勿离开当前页面，超过3次系统将自动提交', '考试注意事项', {
              confirmButtonText: '确定',
              callback: action => {

              }
            })
          }*/
        },


          startTime() {
            if (this.timeValue === '0:00:00' || this.timeValue === '00:00:00') {
              clearInterval(this.timeTarget)
              this.$notify({
                title: '警告',
                duration: 2000,
                message: '考试时间到,系统将自动提交本次考试',
                type: 'warning'
              })
              setTimeout(() => {
                this.timeOutFlag = true
              }, 100)
              return false
            }
            let nowTime = new Date().getTime();
            let chaTime = this.endTime - nowTime;
            //倒计时的时间
            if (chaTime >= 0) {
              let d = Math.floor(chaTime / 1000 / 60 / 60 / 24);
              let h = Math.floor(chaTime / 1000 / 60 / 60 % 24);
              if (h <= 9) {
                h = 0 + '' + h
              }
              let m = Math.floor(chaTime / 1000 / 60 % 60);
              if (m <= 9) {
                m = 0 + '' + m
              }
              let s = Math.floor(chaTime / 1000 % 60);
              if (s <= 9) {
                s = 0 + '' + s
              }
              if (d > 0) {
                this.timeValue = d + '天' + h + '时' + m + '分' + s + '秒'
              } else {
                this.timeValue = h + ':' + m + ':' + s
              }
            }
            this.examTime = this.examTime - 1000
            // 缓存考试时间，防止刷新页面考试时间仍然不变的问题
            sessionStorage.setItem('examTime', this.examTime)
          },

          selectQuestion (index) {

          },

          // 答题卡
          openAnswerSheet () {
            this.openAnswerFlag = true
          },


          // 获取试卷试题列表
          getPaperQuestionList () {
            this.axios.get(this.$httpApi.httpUrl('/student/testPaperInfo/selectPaperQuestionById'), {
              params: {
                id: this.testPaperInfo.id
              }
            }).then(response => {
              this.testPaperInfoQuestionList = response.data.data.dataList
              this.testPaperInfoQuestionList.forEach(item =>{
                let questionType = item.questionType
                if (questionType !== 1 && questionType !== 6) {
                  this.$set(item, 'studentAnswer', [])
                //  item.studentAnswer = [] 此方式会导致v-model 无法绑定变量
                } else {
                  this.$set(item, 'studentAnswer', '')
                }
              })
            })
          },

          afterCommit (questionAnswerParam) {
            clearInterval(this.studentExamTimer)
            let params = {
              examTime: this.studentExamTime,
              testPaperInfoId: this.testPaperInfo.id,
              questionAnswerList: questionAnswerParam
            }
            this.axios.post(this.$httpApi.httpUrl('/student/testPaperInfo/commitPaper'), params)
              .then(response => {
                this.$message.success('提交成功')
                this.$router.push('examHistory')
            })
          }
        },

        filters: {

        }
    }
</script>

<style scoped>

  .exam_time {
    color: red;
    font-size: 24px;
    position: relative;
    left: 30%;
    bottom: 80%
  }

  .back{
    color:#ca0000;
    cursor: pointer;
  }

  .text {
    font-size: 14px;
  }
  .oper-btn {
    position: relative;
    left: 35%;
    margin-top: 50px;
  }
  .radio-item {
    line-height: 40px; margin-left: 20px
  }
  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }
  .box-card p {display: inline}
  .box-card {
    width: 100%;
  }
  .box-card >>> p {display: inline-block}
</style>
